<template>
  <div class="resources-manager-page">
    <div class="manager-header">
      <div class="header-title">
        <el-icon class="header-icon"><Files /></el-icon>
        <h2>我的资源管理</h2>
      </div>
      <div class="header-stats">
        <div class="stat-card">
          <el-icon class="stat-icon"><Document /></el-icon>
          <div class="stat-info">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总资源数</div>
          </div>
        </div>
        <el-button type="primary" class="refresh-btn" @click="fetchMyResources" :loading="loading">
          <el-icon class="btn-icon"><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="myResources" style="width: 100%" v-loading="loading" empty-text="暂无资源" class="modern-table">
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <div class="title-cell">
              <el-icon class="title-icon">
                <Document v-if="scope.row.fileType === '.pdf' || scope.row.fileType === '.doc' || scope.row.fileType === '.docx'" />
                <Notebook v-else-if="scope.row.fileType === '.ppt' || scope.row.fileType === '.pptx'" />
                <Grid v-else-if="scope.row.fileType === '.xls' || scope.row.fileType === '.xlsx'" />
                <FolderOpened v-else-if="scope.row.fileType === '.zip'" />
                <Edit v-else-if="scope.row.fileType === '.md'" />
                <MoreFilled v-else />
              </el-icon>
              <span class="title-text">{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="类型" width="120">
          <template #default="scope">
            <el-tag class="type-tag" type="info">
              <el-icon class="tag-icon"><Paperclip /></el-icon>
              {{ scope.row.fileType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="scope">
            <div class="size-cell">
              <el-icon class="size-icon"><DataBoard /></el-icon>
              <span>{{ formatSize(scope.row.fileSize) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="上传时间" width="140">
          <template #default="scope">
            <div class="time-cell">
              <el-icon class="time-icon"><Clock /></el-icon>
              <span>{{ formatDate(scope.row.createdAt) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="downloadCount" label="下载数" width="100">
          <template #default="scope">
            <div class="count-cell">
              <el-icon class="count-icon download-icon"><Download /></el-icon>
              <span>{{ scope.row.downloadCount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞数" width="100">
          <template #default="scope">
            <div class="count-cell">
              <el-icon class="count-icon like-icon"><StarFilled /></el-icon>
              <span>{{ scope.row.likeCount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center">
          <template #default="scope">
            <el-popconfirm title="确定要删除该资源吗？" @confirm="deleteResource(scope.row)">
              <template #reference>
                <el-button class="delete-btn" size="small">
                  <el-icon class="btn-icon"><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
      v-model:current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
      class="custom-pagination"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getUserResourcePage,updateResourceStatus } from '../../api/resources'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/user'
import { 
  Files, Document, Refresh, Notebook, Grid, FolderOpened, Edit, MoreFilled, 
  Paperclip, DataBoard, Clock, Download, StarFilled, Delete 
} from '@element-plus/icons-vue'

const userStore = useUserStore()
const myResources = ref<any[]>([])
const loading = ref(false)
const userId = Number(userStore.id)
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)

const fetchMyResources = async () => {
  loading.value = true
  try {
    console.log('获取用户资源，userId:', userId, 'pageNum:', pageNum.value, 'pageSize:', pageSize.value)
    const res = await getUserResourcePage({ pageNum: pageNum.value, pageSize: pageSize.value, userId })
    // res.data 就是分页数据，没有 code 字段
    console.log('res.data', res.data)
    if (Array.isArray(res.data.records)) {
      myResources.value = res.data.records
      total.value = res.data.total
    } else {
      myResources.value = []
      total.value = 0
    }
  } catch (e: any) {
    ElMessage.error(e.message || '获取资源失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (p: number) => {
  pageNum.value = p
  fetchMyResources()
}

const deleteResource = async (item: any) => {
  loading.value = true
  try {
    const res = await updateResourceStatus(item.id,0) // 0表示删除状态
    console.log('删除返回：', res)
    //检查响应结构
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchMyResources()
    } else {
      ElMessage.error(res.data?.message || '删除失败')
    }
  } catch (e: any) {
    ElMessage.error(e.message || '删除失败')
  } finally {
    loading.value = false
  }
}

const formatSize = (size: number) => {
  if (!size) return '0B'
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
  if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(1) + 'MB'
  return (size / 1024 / 1024 / 1024).toFixed(1) + 'GB'
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return dateStr
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

onMounted(fetchMyResources)
</script>

<style scoped>
/* 主容器样式 */
.resources-manager-page {
  max-width: 1200px;
  height: 800px;
  margin: 0 auto;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(252, 250, 255, 0.98) 100%);
  border-radius: var(--radius-xl, 16px);
  box-shadow: 0 8px 40px rgba(162, 89, 236, 0.15), 0 4px 16px rgba(162, 89, 236, 0.1);
  padding: 40px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(162, 89, 236, 0.1);
}

/* 头部样式 */
.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 2px solid rgba(162, 89, 236, 0.1);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  /* 保证图标和标题在同一行 */
}

.header-title h2 {
  font-size: 2.2rem;
  font-weight: 700;
  background: linear-gradient(135deg, #a259ec 0%, #5b6ee1 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 8px 0;
  /* 移除 display: flex;，由父级控制布局 */
  /* align-items: center; 由父级控制 */
  gap: 0;
}

.header-icon {
  font-size: 2.2rem;
  color: var(--primary-purple, #a259ec);
}

.header-subtitle {
  color: var(--text-muted, #6b7280);
  font-size: 16px;
  margin-top: 8px;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 24px;
}

.stat-card {
  background: linear-gradient(135deg, rgba(162, 89, 236, 0.1) 0%, rgba(91, 110, 225, 0.1) 100%);
  padding: 20px;
  border-radius: var(--radius-lg, 12px);
  border: 1px solid rgba(162, 89, 236, 0.15);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  min-width: 140px;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(162, 89, 236, 0.2);
}

.stat-icon {
  font-size: 32px;
  color: var(--primary-purple, #a259ec);
  background: rgba(255, 255, 255, 0.8);
  padding: 12px;
  border-radius: 50%;
}

.stat-info {
  text-align: left;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: var(--primary-purple, #a259ec);
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--text-muted, #6b7280);
  margin-top: 4px;
}

.refresh-btn {
  background: linear-gradient(135deg, #a259ec 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: var(--radius-md, 8px);
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #9333ea 0%, #7c3aed 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(162, 89, 236, 0.3);
}

/* 表格容器 */
.table-container {
  margin-bottom: 12px; /* 原为32px，减小高度 */
  height:350px;
  border-radius: var(--radius-lg, 12px);
  overflow: hidden;
  border: 1px solid rgba(162, 89, 236, 0.1);
}

.modern-table {
  border-radius: var(--radius-lg, 12px);
  background: rgba(255, 255, 255, 0.95);
  overflow: hidden;
}

.modern-table :deep(.el-table__header) {
  background: linear-gradient(135deg, rgba(162, 89, 236, 0.1) 0%, rgba(91, 110, 225, 0.1) 100%);
}

.modern-table :deep(.el-table__header th) {
  background: transparent;
  color: var(--primary-purple, #a259ec);
  font-weight: 600;
  border-bottom: 2px solid rgba(162, 89, 236, 0.2);
  padding: 8px 6px; /* 原为16px 12px，减小高度 */
}

.modern-table :deep(.el-table__body tr) {
  transition: all 0.3s ease;
}

.modern-table :deep(.el-table__body tr:hover) {
  background: rgba(162, 89, 236, 0.05);
}

.modern-table :deep(.el-table__body td) {
  padding: 8px 6px; /* 原为16px 12px，减小高度 */
  border-bottom: 1px solid rgba(162, 89, 236, 0.1);
}

/* 表格单元格样式 */
.title-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-icon {
  font-size: 18px;
  color: var(--primary-blue, #3b82f6);
  background: rgba(59, 130, 246, 0.1);
  padding: 8px;
  border-radius: 50%;
}

.title-text {
  font-weight: 500;
  color: var(--text-primary, #1f2937);
}

.type-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: var(--radius-sm, 6px);
  font-weight: 500;
  background: linear-gradient(135deg, rgba(91, 110, 225, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%);
  border: 1px solid rgba(91, 110, 225, 0.2);
  color: var(--primary-blue, #3b82f6);
}

.tag-icon {
  font-size: 14px;
}

.size-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: var(--text-secondary, #6b7280);
}

.size-icon {
  font-size: 16px;
  color: var(--primary-green, #10b981);
}

.count-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
}

.count-icon {
  font-size: 16px;
}

.like-icon {
  color: #ef4444;
}

.download-icon {
  color: #059669;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
}

.time-icon {
  font-size: 14px;
  color: var(--primary-purple, #a259ec);
}

/* 删除按钮 */
.delete-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  border: none;
  border-radius: var(--radius-sm, 6px);
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3);
}

.btn-icon {
  font-size: 14px;
}

/* 分页样式 */
.custom-pagination {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

.custom-pagination :deep(.el-pager li) {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(162, 89, 236, 0.2);
  border-radius: var(--radius-md, 8px);
  margin: 0 4px;
  transition: all 0.3s ease;
  color: var(--text-secondary, #6b7280);
}

.custom-pagination :deep(.el-pager li:hover),
.custom-pagination :deep(.el-pager li.is-active) {
  background: linear-gradient(135deg, #a259ec 0%, #8b5cf6 100%);
  color: white;
  border-color: transparent;
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(162, 89, 236, 0.3);
}

.custom-pagination :deep(.btn-prev),
.custom-pagination :deep(.btn-next) {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(162, 89, 236, 0.2);
  border-radius: var(--radius-md, 8px);
  color: var(--text-secondary, #6b7280);
  transition: all 0.3s ease;
}

.custom-pagination :deep(.btn-prev:hover),
.custom-pagination :deep(.btn-next:hover) {
  background: linear-gradient(135deg, #a259ec 0%, #8b5cf6 100%);
  color: white;
  border-color: transparent;
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(162, 89, 236, 0.3);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .resources-manager-page {
    padding: 24px;
  }
  
  .manager-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .header-stats {
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .resources-manager-page {
    padding: 16px;
  }
  
  .header-title h2 {
    font-size: 1.8rem;
  }
  
  .stat-card {
    min-width: auto;
    padding: 16px;
  }
  
  .modern-table :deep(.el-table__body td),
  .modern-table :deep(.el-table__header th) {
    padding: 12px 8px;
  }
}

/* 为了确保按钮不会使用默认主题色，强制设置样式 */
.el-button:focus {
  outline: none !important;
  box-shadow: none !important;
}
</style>
